import { ref, watch } from 'vue'
import useCategoryStore from '@/store/modules/category'
import { ProductApi } from '@/api/product'
import { SpuModel } from '@/api/product/type'

export const useSpu = () => {
  const categoryStore = useCategoryStore()

  const scene = ref<number>(0)
  const page = ref<number>(1)
  const limit = ref<number>(10)
  const total = ref<number>(0)
  const spuList = ref<SpuModel[]>([])

  watch(
    () => categoryStore.c3,
    async () => {
      if (!categoryStore.c3) return
      await getProductList()
    }
  )

  // 当每页数量发生变化的时候
  const handleSizeChange = async (value: number) => {
    limit.value = value
    await getProductList()
  }

  const getProductList = async (pager: number = 1) => {
    try {
      page.value = pager
      let response = await ProductApi.getProductList(page.value, limit.value, categoryStore.c3)
      total.value = response.total
      spuList.value = response.records
    } catch (error) {}
  }

  return {
    categoryStore,
    page,
    limit,
    total,
    spuList,
    getProductList,
    handleSizeChange
  }
}
